package com.bootdo.app.controller;

import com.alibaba.fastjson.JSON;
import com.bootdo.app.common.utils.ContextHandlerUtil;
import com.bootdo.app.dto.wx.UserDataDto2;
import com.bootdo.app.service.BackGroundService;
import com.bootdo.app.service.WXService;
import com.bootdo.common.config.BootdoConfig;
import com.bootdo.common.utils.HttpUtil;
import com.bootdo.common.wx.WeiXinUtil;
import com.bootdo.system.controller.PunchBackground;
import com.bootdo.system.dao.PunchBackgroundDao;
import com.bootdo.system.domain.TbWeixinconfig;
import com.bootdo.system.domain.TbWxmenu;
import com.bootdo.system.domain.TbWxuser;
import com.bootdo.system.mapper.TbWxuserMapper;
import com.bootdo.system.service.WxConfigService;
import com.bootdo.system.service.WxMenuService;
import com.google.gson.JsonObject;

import org.apache.http.client.ClientProtocolException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;

import java.awt.AlphaComposite;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.Transparency;
import java.awt.geom.Ellipse2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;

/**
 * @auther: 作者: Along
 * @description: 用户邀请
 */
@RestController
@RequestMapping(value = "/app/user_invite")
public class QrcodeController {


    @Autowired
    private TbWxuserMapper wxuserMapper;
    
    @Autowired
	private BootdoConfig bootdoConfig;
    
    
	@Autowired
	private WxConfigService wxConfigService;
	
	@Autowired
	private WxMenuService wxMenuService;
	@Autowired
	private WXService wXService;
	@Autowired
	private PunchBackgroundDao punch;
	

    /**
     * 生成当前用户邀请二维码
     * @throws IOException 
     */
//    @PostMapping(value = "/qrcode")
//    public String qrcode(HttpServletResponse response) throws IOException{
//        String currentUserId = ContextHandlerUtil.getCurrentUserId();
//        TbWxuser tbWxuser = wxuserMapper.selectByPrimaryKey(Integer.valueOf(currentUserId));
//        String headimgurl = tbWxuser.getHeadimgurl();
//        String renameToUUID = FileUtil.renameToUUID(tbWxuser.getId()+"");
//        String uploadPath = bootdoConfig.getUploadPath()+renameToUUID+".png";
//        OutputStream outQRCode = new FileOutputStream(new File(uploadPath));
//        QRCodeUtil.drawLogoQRCode(HttpUtil.createGet(headimgurl).execute().bodyStream(),outQRCode,tbWxuser.getId()+"",IMG_FORMAT);
//        String res="/upLoad/"+renameToUUID+".png";
//        return res;
//    }
    
    
//  @PostMapping(value = "/weChatMa")
//  public String weChatMa(@RequestBody  UserDataDto2 userDataDto) throws ClientProtocolException, IOException {
//	  String currentUserId = ContextHandlerUtil.getCurrentUserId();
//	  //获取当前openId
//      TbWxuser tbWxuser = wxuserMapper.selectByPrimaryKey(Integer.valueOf(currentUserId));
//      //拼接参数
//      String parameter = tbWxuser.getId()+"";
//      String key = UUID.randomUUID() + ".png";
//      String res="/upLoad/"+key;
//      //获取微信token
//	  TbWeixinconfig selectByAppId = wxConfigService.selectByAppId(userDataDto.getAppId());
//	  String accessToken =WeiXinUtil.getOauth2AccessToken2(selectByAppId.getAppid(), selectByAppId.getAppsecret());
//	  try{
//	        URL url = new URL("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+accessToken);
//	        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
//	        // conn.setConnectTimeout(10000);//连接超时 单位毫秒
//	        // conn.setReadTimeout(2000);//读取超时 单位毫秒
//	        // 发送POST请求必须设置如下两行
//	        httpURLConnection.setDoOutput(true); // 打开写入属性
//	        httpURLConnection.setDoInput(true); // 打开读取属性
//	        httpURLConnection.setRequestMethod("POST");// 提交方式
//	        // 不得不说一下这个提交方式转换！！真的坑。。改了好长时间！！一定要记得加响应头
//	        httpURLConnection.setRequestProperty("Content-Type", "application/x-javascript; charset=UTF-8");// 设置响应头
//	        // 获取URLConnection对象对应的输出流
//	        PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
//	        // 发送请求参数
//	        JSONObject paramJson = new JSONObject();
//	        paramJson.put("scene", parameter); // 你要放的内容
//	        paramJson.put("path", "pages/index/index");
//	        paramJson.put("width", 430); // 宽度
//	        paramJson.put("auto_color", true);
//	        printWriter.write(paramJson.toString());
//	        // flush输出流的缓冲
//	        printWriter.flush();
//	        BufferedInputStream bis = new BufferedInputStream(httpURLConnection.getInputStream());
//	        OutputStream os = new FileOutputStream(new File(bootdoConfig.getUploadPath()+key));
//	        System.out.println(key);
//	        int len;
//	        byte[] arr = new byte[1024];
//	        while ((len = bis.read(arr)) != -1)
//	        {
//	            os.write(arr, 0, len);
//	            os.flush();
//	        }
//	        os.close();
//	    }
//	    catch (Exception e)
//	    {
//	        e.printStackTrace();
//	    }
//      return res;
//  }
//  
  @PostMapping(value = "/weChatYqMa")
  public List<String> weChatMa(@RequestBody  UserDataDto2 userDataDto) throws ClientProtocolException, IOException {
	  String currentUserId = ContextHandlerUtil.getCurrentUserId();
	  //获取当前openId
      TbWxuser tbWxuser = wxuserMapper.selectByPrimaryKey(Integer.valueOf(currentUserId));
      //拼接参数
	  TbWeixinconfig wxConfig = wxConfigService.selectByAppId(userDataDto.getAppId());
	  Integer adminId = wxConfig.getAdminId();
	  TbWxmenu selectByAppId =wxMenuService.selectByUserId(adminId);
	  
      String res="https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=";
      String sceneStr="yq"+"@"+tbWxuser.getId();
      //获取微信token
      String accessToken= wXService.getAccessToken(selectByAppId.getAppid(), selectByAppId.getAppsecret());
//	  String accessToken =WeiXinUtil.getOauth2AccessToken2(selectByAppId.getAppid(), selectByAppId.getAppsecret());
	  String createForeverTicket = createForeverTicket(accessToken, sceneStr);
//	  String downloadPicture = downloadPicture(res+createForeverTicket);
	  String cc= bootdoConfig.getUploadPath()+"images/"+"poster.png";

	  Map maps = new HashMap();
      maps.put("adminId",tbWxuser.getSid());
      List aa = punch.selectPunchBackgroundList(maps);
              //backGroundService.selectAdminBackGround();
	  List list = new ArrayList();
	  if(aa.size()<=0){
          String key = UUID.randomUUID() + ".png";
          drawPoster(cc,res+createForeverTicket,bootdoConfig.getUploadPath()+key);
          String resq=bootdoConfig.getSsl()+"/upLoad/"+key;
          list.add(resq);
      }else{
          for(Object map : aa){
              String key = UUID.randomUUID() + ".png";
              HashMap hashMap = (HashMap) map;
              drawPoster((String) hashMap.get("punchImg"),res+createForeverTicket,bootdoConfig.getUploadPath()+key);
              String resq=bootdoConfig.getSsl()+"/upLoad/"+key;
              list.add(resq);
          }


      }


      return list;
  }
  
  @PostMapping(value = "/weChatPtMa")
  public String weChatPtMa(@RequestBody  UserDataDto2 userDataDto) throws ClientProtocolException, IOException {
	  String currentUserId = ContextHandlerUtil.getCurrentUserId();
	  //获取当前openId
      TbWxuser tbWxuser = wxuserMapper.selectByPrimaryKey(Integer.valueOf(currentUserId));
      //拼接参数
      TbWeixinconfig wxConfig = wxConfigService.selectByAppId(userDataDto.getAppId());
	  Integer adminId = wxConfig.getAdminId();
	  TbWxmenu selectByAppId =wxMenuService.selectByUserId(adminId);
      String res="https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=";
      String sceneStr="pt"+"@"+tbWxuser.getId()+"@"+userDataDto.getGroupBuyId();
      //获取微信token
      String accessToken= wXService.getAccessToken(selectByAppId.getAppid(), selectByAppId.getAppsecret());

//	  String accessToken =WeiXinUtil.getOauth2AccessToken2(selectByAppId.getAppid(), selectByAppId.getAppsecret());
	  String createForeverTicket = createForeverTicket(accessToken, sceneStr);
//	  String downloadPicture = downloadPicture(res+createForeverTicket);
	 String aa= bootdoConfig.getUploadPath()+"images/"+"poster.png";
	  //String aa = (String) backGroundService.selectAdminBackGround().get("url");
	 String key = UUID.randomUUID() + ".png";
	  drawPoster(aa,res+createForeverTicket,bootdoConfig.getUploadPath()+key);
	  String resq=bootdoConfig.getSsl()+"/upLoad/"+key;
      return resq;
  }
  
  
  private  String downloadPicture(String urlList) {
      URL url = null;
      String key = UUID.randomUUID() + ".png";
      //本地地址及名称
        String imageName =  bootdoConfig.getUploadPath()+key;
        String res="/upLoad/"+key;
      try {
          url = new URL(urlList);
          DataInputStream dataInputStream = new DataInputStream(url.openStream());
          FileOutputStream fileOutputStream = new FileOutputStream(new File(imageName));
          ByteArrayOutputStream output = new ByteArrayOutputStream();

          byte[] buffer = new byte[1024];
          int length;

          while ((length = dataInputStream.read(buffer)) > 0) {
              output.write(buffer, 0, length);
          }
          byte[] context=output.toByteArray();
          fileOutputStream.write(output.toByteArray());
          dataInputStream.close();
          fileOutputStream.close();
      } catch (MalformedURLException e) {
          e.printStackTrace();
      } catch (IOException e) {
          e.printStackTrace();
      }
      return res;
  }

  
  /**
   * 创建永久二维码(字符串)
   *
   * @param accessToken
   * @param sceneStr    场景str
   * @return
   */
  public  String createForeverTicket(String accessToken, String sceneStr) {
  	String resurl="https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token="+accessToken;
      TreeMap<String, String> params = new TreeMap<>();
      params.put("access_token", accessToken);
      // output data
      JsonObject data = new JsonObject();
      data.addProperty("action_name", "QR_LIMIT_STR_SCENE");
      JsonObject actionInfo = new JsonObject();
      JsonObject scene = new JsonObject();
      scene.addProperty("scene_str", sceneStr);
      actionInfo.add("scene", scene);
      data.add("action_info", actionInfo);
      String result = HttpUtil.doPost(resurl, params, data.toString());
      System.out.println(result);
      HashMap hashMap = JSON.parseObject(result, HashMap.class);
      return (String) hashMap.get("ticket");
  }
  
  
  /**
	 * @Author:pibigstar
	 * @Description: 画海报
	 */
	public  void drawPoster(String BACKGROUND_IMG,String avatar_img,String result_img) {
		try {
			// 1. 创建画布
			BufferedImage backgroundImg = ImageIO.read(getInputStream(BACKGROUND_IMG));
			BufferedImage canvas = new BufferedImage(backgroundImg.getWidth(), backgroundImg.getHeight(),
					BufferedImage.TYPE_INT_RGB);
			Graphics2D g = (Graphics2D) canvas.getGraphics();
			
			canvas = g.getDeviceConfiguration().createCompatibleImage(backgroundImg.getWidth(), backgroundImg.getHeight(), Transparency.TRANSLUCENT);
			 g.dispose();
			 g = canvas.createGraphics();
			// 设置抗锯齿
			g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB);

			// 2. 将头像设置为圆角
			BufferedImage avatar = ImageIO.read(new URL(avatar_img));
			BufferedImage newAvatar = new BufferedImage(avatar.getWidth(), avatar.getHeight(),
					BufferedImage.TYPE_INT_ARGB);
			Ellipse2D.Double shape = new Ellipse2D.Double(0, 0, avatar.getWidth(), avatar.getHeight());
			Graphics2D g2 = newAvatar.createGraphics();
			newAvatar = g2.getDeviceConfiguration().createCompatibleImage(avatar.getWidth(), avatar.getHeight(),
					Transparency.TRANSLUCENT);
			g2 = newAvatar.createGraphics();
			g2.setComposite(AlphaComposite.Clear);
			g2.fill(new Rectangle(newAvatar.getWidth(), newAvatar.getHeight()));
			g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC, 0.0f));
			g2.setClip(shape);
			// 使用 setRenderingHint 设置抗锯齿
			g2 = newAvatar.createGraphics();
			g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
			g2.fillRoundRect(0, 0, avatar.getWidth(), avatar.getHeight(), 0, 0);
			g2.setComposite(AlphaComposite.SrcIn);
			g2.drawImage(avatar, 0, 0, avatar.getWidth(), avatar.getHeight(), null);
			g2.dispose();

			// 3. 将背景图和头像结合
			// 画背景
			g.drawImage(backgroundImg.getScaledInstance(backgroundImg.getWidth(), backgroundImg.getHeight(),
					Image.SCALE_DEFAULT), 0, 0, null);
			// 背景上画头像
			g.drawImage(newAvatar.getScaledInstance(150, 150, Image.SCALE_DEFAULT), 68, 260, null);

			// 画竖着的文字
			g.dispose();
			File resultImg = new File(result_img);
			ImageIO.write(canvas, "png", resultImg);
//			System.out.println("生成成功！");
//			System.out.println("耗时: " + (System.currentTimeMillis() - startTime) / 1000.0 + "s");
//			System.out.println("生成文件路径: " + resultImg.getAbsolutePath());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


	/**
	 * 获取resources下的文件输入流
	 * @throws FileNotFoundException 
	 */
	private  InputStream getInputStream(String fileName) throws FileNotFoundException {
		File f= new File(fileName);
		InputStream input=new  FileInputStream(f);
		return input;
	}

}
